<template>
  <div class="container">
    <el-row>
      <el-col :span="4">
        <el-tree
          :default-expand-all="true"
          :data="deptOptions"
          :props="defaultProps"
          @node-click="handleNodeClick"
        />
      </el-col>
      <el-col :span="20">
        <div>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="openDialog('新增')"
          >新增</el-button>
          <el-button
            type="danger"
            size="mini"
            class="el-icon-delete"
            :disabled="multipleSelection.length == 0"
            @click="deletes()"
          >删除</el-button>
        </div>
        <el-table
          :data="tableData"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            align="center"
            type="selection"
            width="55"
          />
          <el-table-column
            label="用户名称"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="手机号码"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.phone }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.isBanned == "0" ? "正常" : "禁用" }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdOn) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="openEtidDialog('修改', scope.row)"
              >编辑</el-button>
              <el-button
                type="text"
                size="mini"
                icon="el-icon-delete"
                @click="deleteRow(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          class="pagination"
          background
          :current-page="queryParams.pageIndex"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <el-dialog
          :title="dialogSetting.title"
          :visible.sync="dialogSetting.dialogVisible"
          :width="dialogSetting.width"
          :close-on-press-escape="false"
          :close-on-click-modal="false"
          :before-close="beforeCloseDialog"
        >
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            label-width="80px"
            :rules="rules"
          >
            <el-form-item
              label="归属部门"
              prop="deptId"
            >
              <treeselect
                v-model="ruleForm.deptId"
                :options="deptOptions"
                :clearable="false"
                :close-on-select="true"
                placeholder="请选择部门"
                :flatten-search-results="true"
                :normalizer="normalizer"
              />
            </el-form-item>
            <el-form-item
              label="用户名称"
              prop="username"
            >
              <el-input v-model="ruleForm.username" />
            </el-form-item>
            <!-- <el-form-item
              label="登录密码"
              prop="password"
            >
              <el-input v-model="ruleForm.password" />
            </el-form-item> -->
            <el-form-item
              label="真是姓名"
              prop="realName"
            >
              <el-input v-model="ruleForm.realName" />
            </el-form-item>
            <el-form-item
              label="手机号"
              prop="phone"
            >
              <el-input v-model="ruleForm.phone" />
            </el-form-item>
            <el-form-item
              label="默认头像"
              prop="avatar"
            >
              <el-avatar :src="ruleForm.avatar" />
            </el-form-item>
            <el-form-item
              label="性别"
              prop="gender"
            >
              <el-select
                v-model="ruleForm.gender"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in genderOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="邮箱"
              prop="email"
            >
              <el-input v-model="ruleForm.email" />
            </el-form-item>
            <el-form-item
              label="岗位"
              prop="jobId"
            >
              <el-select
                v-model="ruleForm.jobId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in jobOptions"
                  :key="item.id"
                  :label="item.jobName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="角色"
              prop="roleIds"
            >
              <el-select
                v-model="ruleForm.roleIds"
                placeholder="请选择"
                style="width: 100%"
                multiple
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="dialogSetting.title === '修改'"
              label="状态"
              prop="isBanned"
            >
              <el-radio-group v-model="ruleForm.isBanned">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="备注"
              prop="remark"
            >
              <el-input
                v-model="ruleForm.remark"
                type="textarea"
              />
            </el-form-item>
          </el-form>
          <span
            slot="footer"
            class="dialog-footer"
          >
            <el-button
              size="small"
              @click="closeDialog()"
            >取 消</el-button>
            <el-button
              type="primary"
              size="small"
              @click="sub('ruleForm')"
            >确 定</el-button>
          </span>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { getListTree } from '@/api/upms/dept'
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { dictItemList } from '@/api/upms/dict-item'
import { getJobList } from '@/api/upms/job'
import {
  create,
  getPageList,
  userDetailById,
  update,
  deletesUser
} from '@/api/upms/user'
import { getRoleList } from '@/api/upms/role'
export default {
  name: 'User',
  components: { Treeselect },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        deptId: ''
      },
      tableData: [],
      genderOptions: [], // 性别
      jobOptions: [], // 岗位
      roleOptions: [], // 角色
      total: 0,
      multipleSelection: [], // 选项集合
      deptOptions: [],
      dialogSetting: {
        dialogVisible: false,
        title: '',
        width: '30%'
      },
      ruleForm: {
        id: null,
        remark: '',
        isBanned: '0',
        username: '',
        password: '123456',
        realName: '',
        phone: '',
        avatar: 'http://localhost:9000/wuzhihang/marmot.jpg',
        gender: '',
        email: '',
        deptId: null,
        jobId: '',
        roleId: []
      },
      resetRuleForm: {
        id: null,
        remark: '',
        isBanned: '0',
        username: '',
        password: '',
        realName: '',
        phone: '',
        avatar: 'http://localhost:9000/wuzhihang/marmot.jpg',
        gender: '',
        email: '',
        deptId: null,
        jobId: '',
        roleIds: []
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        avatar: [
          { required: true, message: '请输入用户头像地址', trigger: 'blur' }
        ],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        email: [{ required: true, message: '请输入用户邮箱', trigger: 'blur' }],
        deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
        jobId: [{ required: true, message: '请输入岗位', trigger: 'change' }],
        roleIds: [
          {
            type: 'array',
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }
        ],
        isBanned: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'change'
          }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'deptName',
        id: 'id'
      }
    }
  },
  created() {
    this.getPageList()
    this.getListTree()
    this.getGenderOptinsList('sys_user_gender')
    this.getRoleOptionsList()
    this.getJobOptionsList()
  },
  methods: {
    // 获取分页列表
    getPageList() {
      getPageList(this.queryParams).then(resp => {
        if (resp.code === 0) {
          this.tableData = resp.data.list
          this.total = resp.data.totalRows
        }
      })
    },
    // 获取性别
    getGenderOptinsList(dictType) {
      dictItemList({ dictType: dictType }).then(resp => {
        if (resp.code === 0) {
          this.genderOptions = resp.data.list
        }
      })
    },
    // 获取岗位
    getJobOptionsList() {
      getJobList().then(resp => {
        if (resp.code === 0) {
          this.jobOptions = resp.data.list
        }
      })
    },
    // 获取角色
    getRoleOptionsList() {
      getRoleList().then(resp => {
        if (resp.code === 0) {
          this.roleOptions = resp.data.list
        }
      })
    },
    // 获取部门tree
    getListTree() {
      getListTree().then(resp => {
        if (resp.code === 0) {
          this.deptOptions = resp.data.list
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.getPageList()
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.deptName,
        children: node.children
      }
    },
    // 每页条目数变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getPageList()
    },
    openEtidDialog(title, rowId) {
      // 获取详情
      this.getDetail(rowId)
    },
    getDetail(row) {
      userDetailById({ id: row.id }).then(resp => {
        if (resp.code === 0) {
          const rowDetail = resp.data.detail
          this.ruleForm.id = rowDetail.id
          this.ruleForm.remark = rowDetail.remark
          this.ruleForm.isBanned = rowDetail.isBanned
          this.ruleForm.username = rowDetail.username
          this.ruleForm.password = rowDetail.password
          this.ruleForm.realName = rowDetail.realName
          this.ruleForm.phone = rowDetail.phone
          this.ruleForm.avatar = rowDetail.avatar
          this.ruleForm.gender = rowDetail.gender
          this.ruleForm.deptId = rowDetail.deptId
          this.ruleForm.jobId = rowDetail.jobId
          this.ruleForm.roleIds = rowDetail.roleIds
          this.ruleForm.email = rowDetail.email
          this.getListTree()
          this.dialogSetting.title = '修改'
          this.dialogSetting.dialogVisible = true
        }
      })
    },
    // 页数变化
    handleCurrentChange(val) {
      this.queryParams.pageIndex = val
      this.getPageList()
    },
    openDialog(title) {
      this.dialogSetting.title = title
      this.dialogSetting.dialogVisible = true
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    beforeCloseDialog(done) {
      this.resetForm('ruleForm')
      this.reset()
      done()
    },
    // 批量删除
    deletes() {
      var arr = []
      this.multipleSelection.forEach(v => {
        arr.push(v['id'])
      })
      deletesUser({ ids: arr }).then(resp => {
        if (resp.code === 0) {
          this.getPageList()
        }
      })
    },
    deleteRow(row) {
      deletesUser({ ids: [row.id] }).then(resp => {
        if (resp.code === 0) {
          this.getPageList()
        }
      })
    },
    closeDialog() {
      this.dialogSetting.dialogVisible = false
      this.resetForm('ruleForm')
      this.reset()
    },
    reset() {
      this.ruleForm = this.resetRuleForm
    },
    sub(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          switch (this.dialogSetting.title) {
            case '新增':
              var createParam = {
                remark: this.ruleForm.remark,
                username: this.ruleForm.username,
                password: this.ruleForm.password,
                realName: this.ruleForm.realName,
                avatar: this.ruleForm.avatar,
                gender: this.ruleForm.gender,
                email: this.ruleForm.email,
                deptId: this.ruleForm.deptId,
                jobId: this.ruleForm.jobId,
                phone: this.ruleForm.phone,
                roleIds: this.ruleForm.roleIds
              }
              create(createParam).then(resp => {
                if (resp.code === 0) {
                  this.notifySuccess('创建成功')
                  this.closeDialog()
                  this.getPageList()
                }
              })
              break
            case '修改':
              var updateParam = {
                id: this.ruleForm.id,
                remark: this.ruleForm.remark,
                username: this.ruleForm.username,
                password: this.ruleForm.password,
                realName: this.ruleForm.realName,
                avatar: this.ruleForm.avatar,
                gender: this.ruleForm.gender,
                email: this.ruleForm.email,
                deptId: this.ruleForm.deptId,
                jobId: this.ruleForm.jobId,
                phone: this.ruleForm.phone,
                roleIds: this.ruleForm.roleIds,
                isBanned: this.ruleForm.isBanned
              }
              update(updateParam).then(resp => {
                if (resp.code === 0) {
                  this.notifySuccess('修改成功')
                  this.closeDialog()
                  this.getPageList()
                }
              })
              break
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/common.scss";
</style>
